import 'package:LifeMusic/api/userApi.dart';
import 'package:LifeMusic/provider/userProvider.dart';
import 'package:LifeMusic/routers/application.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';

import 'dart:convert';
import 'package:convert/convert.dart';
import 'package:crypto/crypto.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

import 'package:LifeMusic/model/userInfoModel.dart';
import 'package:provider/provider.dart';
import 'package:LifeMusic/utils/localStorage.dart';


class LoginPage extends StatelessWidget {
  final String type;
  LoginPage({Key key, this.type}) : super(key: key);
  String account;
  String password;
  String md5Password;
  final loginFormKey=GlobalKey<FormState>();
  //获取表单
  void loginForm(){
    loginFormKey.currentState.save();
    print('username:$account password:$password');
  }
  /// md5加密
  String generateMd5(String data) {
    var content = new Utf8Encoder().convert(data);
    var digest = md5.convert(content);
    return hex.encode(digest.bytes);
  }
  Future loginEmail() async {
    EasyLoading.show(status: '登录中...');
    var result = await GetUserInfoAPi.loginByEmail(account, md5_password: md5Password);
    return result;
  }

  Future loginPhone() async {
    EasyLoading.show(status: '登录中...');
    var result = await GetUserInfoAPi.loginByPhone(account, md5_password: md5Password);
    return result;
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text('登录'),
          backgroundColor: Color(0xff1d1726),
        ),
        backgroundColor: Color(0xff1d1726),
        body: Form(
          key: loginFormKey,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text(
                'WELCOME BACK! ',
                style: TextStyle(color: Colors.white, fontSize: 26),
              ),
              inputTextFiled('请输入手机号/邮箱地址',Icons.account_circle_outlined,callback:(value){
                this.account=value;
              }),
              inputTextFiled('请输入密码',Icons.lock_open_outlined,isPWD:true,callback:(value){
                this.password=value;
                this.md5Password=generateMd5(this.password);
              }),
              Container(
                margin: EdgeInsets.all(20.0),
                height: 40,
                width: MediaQuery.of(context).size.width / 1.1,
                child:Consumer<UserState>(builder: (context, user, child) {
                  return RaisedButton(
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(28),
                      // side: BorderSide(color: Colors.red),
                    ),
                    child: Text('login'),
                    color: Color(0xFFB820FF),
                    onPressed: () {
                      // if(user.loginState){
                      //   print(user.user.profile.nickname);
                      //   }
                      loginForm();
                      if(account==''){
                        EasyLoading.showToast('账号不能为空',toastPosition: EasyLoadingToastPosition.bottom);
                      }else if(password==''){
                        EasyLoading.showToast('密码不能为空',toastPosition: EasyLoadingToastPosition.bottom);
                      }else{
                        if(account.length<=11){
                          loginPhone().then((value){
                            user.loginState=true;
                            user.userInfo=value;
                            LocalStorage.setString('userInfo', jsonEncode(value));
                            Application.router.navigateTo(context, '/homePage',clearStack:true);
                          }).catchError((err){

                          }).whenComplete(() => EasyLoading.dismiss());
                        }else{
                          loginEmail().then((value){
                            user.loginState=true;
                            user.userInfo=value;
                            LocalStorage.setString('userInfo', jsonEncode(value));
                            Application.router.navigateTo(context, '/homePage',clearStack:true);
                          }).catchError((err){
                              print('$err');
                          }).whenComplete(() => EasyLoading.dismiss());
                        }
                      }
                    },
                  );
                })
              )
            ],
          ),
        ));
  }
  Widget inputTextFiled(String hintText, IconData icon, {bool isPWD=false,Function callback}){
    return  Container(
      height: 40,
      margin: EdgeInsets.all(20),
      child: TextFormField(
        onSaved: (value){
          callback(value);
        },
        obscureText: isPWD,
        style: TextStyle(
          color: Colors.white,
          fontSize: 16,
        ),
        decoration: InputDecoration(
          hintText: hintText,
          hintStyle: TextStyle(color:Colors.white, fontSize: 12, fontWeight: FontWeight.w600),
          enabledBorder: OutlineInputBorder(
            borderSide: BorderSide(color: Color(0xFFB820FF)),
            borderRadius: BorderRadius.all(
              Radius.circular(50),
            ),
          ),
          focusedBorder: OutlineInputBorder(
            borderSide: BorderSide(color: Color(0xFFB820FF)),
            borderRadius: BorderRadius.all(
              Radius.circular(50),
            ),
          ),
          contentPadding: EdgeInsets.only(
            top: 0,
            bottom: 0,
          ),
          prefixIcon: Icon(
            icon,
            color: Color(0xFFFFFFFF),
          ),
        ),
      ),
    );
  }
}
